# -*- encoding:utf-8 -*-
'''
	pymysqlutil.py
	======================
	@descript: 
	@copyright:chinasoft
	@author:cjgong
	@date: 2021-01-27 11:02
	@version:v1.0
'''
import pymysql
import traceback
class  PyMysqlUtil:
    #  创建对象时调用的方法
    def __init__(self):
        #  对象变量是私有
        self.__conn=pymysql.connect(host='172.3.11.9', port=3306, user='root',
                                     password='root123', database='django02', charset='utf8',
                                     cursorclass=pymysql.cursors.DictCursor)
        pass
    #  返回数据库操作对象
    def __enter__(self):
        self.var_cursor=self.__conn.cursor()
        return  self.var_cursor


    def __exit__(self, exc_type, exc_val, exc_tb):
        try:
            if exc_type:                  #  当发生异常时，回滚事务
                self.__conn.rollback()
            else:
                self.__conn.commit()       #  当没有发生异常时，提交事务
                pass
        finally:
            self.close()
            pass
        return False                       #  抛出异常

    def  close(self):
        try:
            if self.var_cursor:
                self.var_cursor.close()
                pass
        except:
            traceback.print_exc()
        finally:
            try:
                if self.__conn:
                    self.__conn.close()
                    pass
            except:
                traceback.print_exc()
                pass
            pass

        pass
    pass
